#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include "wav.h"

int check_format(WAVHEADER header);
int get_block_size(WAVHEADER header);

int main(int argc, char *argv[])
{
    // Ensure proper usage
    // TODO #1
    if (argc != 3)
    {
        printf("Usage: ./reverse input.wav output.wav\n");
        return 1;
    }
    // Open input file for reading
    // TODO #2
    char *infile = argv[1];
    char *outfile = argv[2];
    FILE *input = fopen(infile, "r");
    if (input == NULL)
    {
        printf("Incorrect input.\n");
        fclose(input);
        return 1;
    }

    // Read header
    // TODO #3
    WAVHEADER fheader;
    fread(&fheader, sizeof(WAVHEADER), 1, input);

    // Use check_format to ensure WAV format
    // TODO #4
    if (check_format(fheader) != 0)
    {
        fclose(input);
        return 1;
    }

    // Open output file for writing
    // TODO #5
    FILE *output = fopen(outfile, "w");
    if (output == NULL)
    {
        printf("Out file is not ok.");
        fclose(input);
        fclose(output);
        return 1;
    }

    // Write header to file
    // TODO #6
    fwrite(&fheader, sizeof(WAVHEADER), 1, output);

    // Use get_block_size to calculate size of block
    // TODO #7
    int size = get_block_size(fheader);

    // Write reversed audio to file
    // TODO #8
    BYTE buffer[size];
    for (fseek(input, 0 - size, SEEK_END); ftell(input) > sizeof(fheader) - size;
         fseek(input, 0 - (size * 2), SEEK_CUR))
    {
        fread(&buffer, size, 1, input);
        fwrite(&buffer, size, 1, output);
    }

    fclose(input);
    fclose(output);
    return 0;
}

int check_format(WAVHEADER header)
{
    // TODO #4

    if (strncmp((const char *) header.format, "WAVE", 4) != 0)
    {
        printf("Not a valid WAV file!\n");
        return 1;
    }
    return 0;
}

int get_block_size(WAVHEADER header)
{
    // TODO #7
    int n;
    n = header.numChannels * (header.bitsPerSample / 8);

    return n;
}
